import path from 'path'

export const saa = {
  data() {
    return {
      affixTags: []
    }
  },
  computed: {
    $_permissionRoutes() {
      return this.$store.state.permission.routes
    }
  },
  watch: {
    $route() {
      if (this.needTagsView) {
        this.addTags()
      }
    }
  },
  mounted() {
    if (this.needTagsView) {
      this.addTags()
    }
  },
  methods: {
    filterAffixTags(routes, basePath = '/') {
      let tags = []
      routes.forEach(route => {
        if (route.meta && route.meta.affix) {
          const tagPath = path.resolve(basePath, route.path)
          tags.push({
            fullPath: tagPath,
            path: tagPath,
            name: route.name,
            meta: { ...route.meta }
          })
        }
        if (route.children) {
          const tempTags = this.filterAffixTags(route.children, route.path)
          if (tempTags.length >= 1) {
            tags = [...tags, ...tempTags]
          }
        }
      })
      return tags
    },
    initTags() {
      const affixTags = (this.affixTags = this.filterAffixTags(this.$_permissionRoutes))
      for (const tag of affixTags) {
        if (tag.name) {
          this.$store.dispatch('tagsView/addVisitedView', tag)
        }
      }
    },
    addTags() {
      console.log('addTags', this.$route)
      const { name } = this.$route
      if (name) {
        this.$store.dispatch('tagsView/addView', this.$route)
      }
      return false
    },
    moveToCurrentTag() {
      const tags = this.$refs.tag
      this.$nextTick(() => {
        for (const tag of tags) {
          if (tag.to.path === this.$route.path) {
            this.$refs.scrollPane.moveToTarget(tag)
            // when query is different then update
            if (tag.to.fullPath !== this.$route.fullPath) {
              this.$store.dispatch('tagsView/updateVisitedView', this.$route)
            }
            break
          }
        }
      })
    }
  }
}

import { ossStsAuthent } from '@/api/attach'
import { generateUploadFileName } from '@/utils'
import OSS from 'ali-oss'
export default {
  data() {
    return {
      showUpload: false,
      percentage: 0,
      loading: false,
      uploaded: false,
      tempFile: null,
      headers: {
        'Access-Control-Allow-Origin': '*'
      },
      domain: '',
      authToken: {},
      appendParams: {}
    }
  },
  computed: {},
  methods: {
    onPreview(f) {
      console.log(f)
    },
    submitUpload() {
      console.log('video submitUpload')
      this.$refs.videoUpload.submit()
    },
    onChange(file) {
      if (!this.tempFile) {
        this.loading = true
        // 此方法如果是大文件时会出现偶尔卡顿
        const reader = new FileReader()
        reader.readAsDataURL(file.raw)
        reader.onload = () => {
          this.tempFile = {
            url: reader.result,
            type: file.raw.type,
            name: file.name
          }
          this.loading = false
          this.percentage = 0
          this.showUpload = true
        }
      }
    },
    /**
     * @description [onUpload 覆盖默认的上传行为，实现自定义上传]
     * @author   shanshuizinong
     * @param    {object}   option [上传选项]
     * @return   {null}   [没有返回]
     */
    async onUpload(option) {
      try {
        const vm = this
        vm.disabled = true
        // 获取OSS配置信息
        // const relativePath = ossData.relativePath
        const date = vm.$moment().format('YYYYMM/DD')
        const relativePath = 'attachments/sts/' + date + '/'
        const client = new OSS(vm.authToken)

        const file = option.file

        const point = file.name.lastIndexOf('.')
        const suffix = file.name.substr(point)
        const fileNames = generateUploadFileName(suffix)

        const uploadOptions = {
          progress: async p => {
            const e = {}
            e.percent = p * 100
            option.onProgress(e)
          },
          partSize: 500 * 1024,
          timeout: 120 * 1000
        }
        // 分片上传文件
        const result = await client.multipartUpload(relativePath + fileNames, file, uploadOptions)
        console.log('upload', result)
        if (result.res.statusCode === 200) {
          // option.onSuccess(ret)
          vm.disabled = false
          return result
        } else {
          vm.disabled = false
          option.onError('上传失败')
        }
      } catch (error) {
        console.error('上传失败', error)
        this.disabled = false
        option.onError('上传失败')
        this.$error(error.message)
      }
    },
    emitInput(val) {
      this.$emit('change', val)
    },
    onRemove() {
      this.tempFile = null
      this.emitInput('')
      console.log('this.video', this.video)
    },
    onDelete() {
      this.$confirm('此操作将删除商品视频, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.onRemove()
      })
    },
    previewUrl(path, type) {
      var url = [this.domain, '/' + path]
      if (type.includes('video')) {
        url.push('?x-oss-process=video/snapshot,t_1000,f_jpg,m_fast')
      }
      return url.join('')
    },
    handleSuccess(res, file) {
      console.log('success file:', file)
      console.log('success res:', res)
      const { name } = res
      var temp = {
        ...file,
        path: '/' + name,
        url: this.previewUrl(name, file.raw.type),
        type: file.raw.type.split('/')[0]
      }
      console.log('success temp:', temp)
      if (this.isArray(this.fileList)) {
        this.$set(this.fileList, this.fileList.length, temp)
      } else {
        this.fileData = temp
      }
    },
    handleProgress(d) {
      this.percentage = d.percent
    },
    beforeUpload(file) {
      // const overflowSize = this.maxAllowFileSize < file.size // 这里做文件大小限制
      // var maxAllowSize = formatFileSize(this.maxAllowFileSize, 0)
      // if (overflowSize) {
      //   this.$message({
      //     message: `上传文件大小不能超过 ${maxAllowSize}!`,
      //     type: 'warning'
      //   })
      // }else{

      // }
      // return !overflowSize
      console.log(file)

      const _self = this
      return new Promise((resolve, reject) => {
        ossStsAuthent()
          .then(res => {
            const { data } = res
            _self.authToken = {
              // yourRegion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
              region: 'oss-' + data.region,
              bucket: data.bucket,
              // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
              accessKeyId: data.AccessKeyId,
              accessKeySecret: data.AccessKeySecret,
              // 填写Bucket名称，例如examplebucket。
              stsToken: data.SecurityToken
            }
            _self.domain = data.host
            resolve(true)
          })
          .catch(err => {
            console.log(err)
            reject(false)
          })
      })
    },
    percentageColor(percentage) {
      if (percentage < 30) {
        return '#909399'
      } else if (percentage < 70) {
        return '#e6a23c'
      } else {
        return '#67c23a'
      }
    }
  }
}
